package com.dailyblue.java.project.power.interceptor;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.project.power.util.ResultCode;
import com.dailyblue.java.project.power.util.ResultTool;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

@Component
public class IsLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("IsLoginInterceptor");
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        // 获取到前端发送过来的token
        String token = request.getHeader("token");
        Object obj = application.getAttribute(token);
        if (obj == null) {
            // 返回错误信息
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            String json = JSONArray.toJSONString(ResultTool.fail(ResultCode.USER_NOT_LOGIN));
            out.println(json);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
